#!/bin/bash
set -e

echo "🚀 开始部署 Dx Fun Group..."

# 配置变量
PROJECT_DIR="/var/www/dx-fun-group"
BACKUP_DIR="/var/backups/dx-fun-group"

# 检查是否为 root 用户
if [[ $EUID -eq 0 ]]; then
   echo "❌ 请不要使用 root 用户运行此脚本"
   exit 1
fi

# 创建备份
echo "📦 创建备份..."
sudo mkdir -p $BACKUP_DIR
sudo cp -r $PROJECT_DIR/apps/frontend/dist $BACKUP_DIR/frontend-$(date +%Y%m%d-%H%M%S) 2>/dev/null || true

# 进入项目目录
cd $PROJECT_DIR

# 拉取最新代码
echo "📥 拉取最新代码..."
git pull origin main

# 安装依赖
echo "📦 安装依赖..."
pnpm install

# 构建项目
echo "🏗️ 构建项目..."
pnpm build:shared
pnpm build:frontend
pnpm build:backend

# 数据库迁移
echo "🗄️ 数据库迁移..."
cd apps/backend && npx prisma db push && cd ../..

# 重启后端服务
echo "🔄 重启后端服务..."
pm2 restart dx-fun-group-backend

# 重载 Nginx
echo "🌐 重载 Nginx..."
sudo systemctl reload nginx

# 健康检查
echo "🔍 健康检查..."
sleep 3
if curl -f http://localhost:3000/health > /dev/null 2>&1; then
    echo "✅ 后端服务正常"
else
    echo "❌ 后端服务异常"
    exit 1
fi

echo "✅ 部署完成！"
echo "前端: https://your-domain.com"
echo "后端健康检查: https://your-domain.com/health"
